package com.xxx.mch.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @date 2020/9/11
 */
@Service
@Slf4j
public class AuthorizationServiceImpl
{
    @Value("${hive.login-name-url}")
    private String loginNameUrl;

    @Value("${hive.site-code}")
    private String siteCode;

    public List<String> getPermissionCodeList(String token, String loginName)
    {
        List<String> permissonCodeList = new ArrayList<>();
        try
        {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.add("sobeyhive-http-token", token);
            HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);

            ResponseEntity<JSONObject> resultEntity = restTemplate.exchange(loginNameUrl, HttpMethod.GET, requestEntity, JSONObject.class, loginName);

            if (HttpStatus.OK == resultEntity.getStatusCode())
            {
                JSONObject result = resultEntity.getBody();
                log.info("权限接口防护参数：{}", result);
                JSONArray funcPermissionJson = result.getJSONArray("funcPermission");
                for (int i = 0; i < funcPermissionJson.size(); i++)
                {
                    JSONObject jsonObject = funcPermissionJson.getJSONObject(i);
                    String permissionCode = jsonObject.getString("permissionCode");
                    if (permissionCode.startsWith("KPI_DEFAULT_kh"))
                    {
                        permissonCodeList.add(permissionCode);
                    }
                }
            }
            else
            {
                log.error("#method# 远程调用失败 httpCode = [{}]", resultEntity.toString());
            }
            return permissonCodeList;
        } catch (Exception e) {
            log.error("获取权限异常: {}", e.getMessage());
            return permissonCodeList;
        }
    }

}
